import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class SupplierManageFrame extends JFrame {
    private JTable supplierTable;
    private DefaultTableModel tableModel;

    public SupplierManageFrame() {
        setTitle("供应商管理");
        setSize(600, 400);
        setLocationRelativeTo(null);

        // 表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("供应商编号");
        tableModel.addColumn("名称");
        tableModel.addColumn("地址");

        supplierTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(supplierTable);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加");
        JButton editBtn = new JButton("修改");
        JButton deleteBtn = new JButton("删除");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(editBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        loadSupplierData();

        // 事件监听
        addBtn.addActionListener(e -> {
            new SupplierEditDialog(null).setVisible(true);
            loadSupplierData();
        });

        editBtn.addActionListener(e -> {
            int selectedRow = supplierTable.getSelectedRow();
            if (selectedRow >= 0) {
                String ono = (String) tableModel.getValueAt(selectedRow, 0);
                new SupplierEditDialog(ono).setVisible(true);
                loadSupplierData();
            } else {
                JOptionPane.showMessageDialog(this, "请选择要修改的行", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteBtn.addActionListener(e -> deleteSupplier());
        refreshBtn.addActionListener(e -> loadSupplierData());
    }

    private void loadSupplierData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM offer")) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("ono"),
                        rs.getString("oname"),
                        rs.getString("oaddress")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteSupplier() {
        int selectedRow = supplierTable.getSelectedRow();
        if (selectedRow >= 0) {
            String ono = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除供应商 " + ono + " 吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement("DELETE FROM offer WHERE ono = ?")) {

                    pstmt.setString(1, ono);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadSupplierData();
                    }
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}

class SupplierEditDialog extends JDialog {
    private JTextField onoField, onameField, oaddressField;
    private boolean isEditMode;

    public SupplierEditDialog(String ono) {
        if (ono == null) {
            setTitle("添加供应商");
            isEditMode = false;
        } else {
            setTitle("修改供应商");
            isEditMode = true;
        }

        setSize(400, 250);
        setModal(true);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(3, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("供应商编号:"));
        onoField = new JTextField();
        if (isEditMode) onoField.setEditable(false);
        panel.add(onoField);

        panel.add(new JLabel("供应商名称:"));
        onameField = new JTextField();
        panel.add(onameField);

        panel.add(new JLabel("供应商地址:"));
        oaddressField = new JTextField();
        panel.add(oaddressField);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> saveSupplier());

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        if (isEditMode) {
            loadSupplierData(ono);
        }
    }

    private void loadSupplierData(String ono) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM offer WHERE ono = ?")) {

            pstmt.setString(1, ono);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                onoField.setText(rs.getString("ono"));
                onameField.setText(rs.getString("oname"));
                oaddressField.setText(rs.getString("oaddress"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveSupplier() {
        String ono = onoField.getText().trim();
        String oname = onameField.getText().trim();
        String oaddress = oaddressField.getText().trim();

        // 验证输入
        if (ono.isEmpty() || oname.isEmpty()) {
            JOptionPane.showMessageDialog(this, "供应商编号和名称不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            PreparedStatement pstmt;

            if (isEditMode) {
                pstmt = conn.prepareStatement(
                        "UPDATE offer SET oname=?, oaddress=? WHERE ono=?");
                pstmt.setString(1, oname);
                pstmt.setString(2, oaddress);
                pstmt.setString(3, ono);
            } else {
                pstmt = conn.prepareStatement(
                        "INSERT INTO offer (ono, oname, oaddress) VALUES (?, ?, ?)");
                pstmt.setString(1, ono);
                pstmt.setString(2, oname);
                pstmt.setString(3, oaddress);
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}